import router from './router'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { NO_REDIRECT_WHITE_LIST } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { loginStateStoreWithOut } from './store/modules/loginState'
const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()
router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  const userState = useUserStoreWithOut()
  userState.setState(loginStateStoreWithOut())
  if (NO_REDIRECT_WHITE_LIST.includes(to.path)) {
    next()
  } else {
    const state = await userState.init()
    if (state === 0) {
      if (from.path === '/loading' || from.path === '/') {
        next('/login')
      } else {
        next(`/login?redirect=${to.path}`)
      }
    } else if (state === 2) {
      next()
    } else {
      next({ ...to, replace: true })
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
